﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using VSA.DataAccess;
using VSA.Interfaces.Entities;
using System.Collections;
using VSA.CommonLibrary;

namespace VSA.Entities
{
    public class CustomerEntity : EntitiesBase, IEntity<Customer>
    {
        public CustomerEntity(VSADataContext dataContext)
        {
            this.DataContext = dataContext;
        }

        #region Set data context
        private VSADataContext _DataContext;
        public VSADataContext DataContext
        {
            set
            {
                this._DataContext = value;
            }
        }
        #endregion

        #region Primary operation on entity: SELECT, INSERT, UPDATE, DELETE
        public IList<Customer> List(int pageNumber)
        {
            var customers = _DataContext.ExecuteQuery<Customer>("SELECT temp.* FROM "
                                                                    + " (SELECT ROW_NUMBER() OVER (ORDER BY CompanyName) AS OrdinalNo,* FROM Customers) temp"
                                                                    + " WHERE temp.OrdinalNo > " + ((pageNumber - 1) * this.NumberOfItemsPerPage).ToString()
                                                                    + " AND temp.OrdinalNo <= " + ((pageNumber) * this.NumberOfItemsPerPage).ToString());
            return customers.ToList<Customer>();
        }
        public void Insert(Customer customer)
        {
            _DataContext.Customers.InsertOnSubmit(customer);
            _DataContext.SubmitChanges();
        }
        public void Update(Customer customer)
        {
            var cust = _DataContext.Customers.Single(c => c.CustomerID.Equals(customer.CustomerID));

            cust.CompanyName = customer.CompanyName;

            _DataContext.SubmitChanges();
        }
        public void Delete(Customer customer)
        {
            var cust = _DataContext.Customers.Single(c => c.CustomerID.Equals(customer.CustomerID));

            _DataContext.Customers.DeleteOnSubmit(cust);
            _DataContext.SubmitChanges();
        }
        #endregion

        #region Set up page function's prerequisites
        public void SetUpPageFunctionPrerequisites()
        {
            this.NumberOfItems = (from c in _DataContext.Customers
                                  select c).Count();
            this.NumberOfPages = this.GetNumberOfPage();
        }
        #endregion

        #region Customer's attributes
        private Customer _Customer;
        public Customer Customer
        {
            get { return _Customer; }
            set { this._Customer = value; }
        }
        #endregion
    }
}
